<template>
	<!--通讯录 增加-->
	<view class="page-content">
		<view class="page-top">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 搜索 -->
			<w-tit leftIcon="arrowleft" color="#595757" background="#fff" fontweight="600" @confirm="rightSearch"
				rightIconNum="two" is_searchs="true">
			</w-tit>
		</view>
		<view class="page-body">
			<w-phones :pageType="pageType" :phones="phones" :is_checked="false" @paramClick="paramClick" :leftNavAdd="false"
				:is_shrink="is_shrink" @changecheck="changecheck" :sel_list="sel_list"></w-phones>
		</view>
		<view class="page-foot" @click="confirm">确认</view>
		<!--弹窗-->
		<w-popup :show="showtip" :type="type1" @change="change1">
			<view class="w-tip">
				<view class="w-tit">是否创建群？</view>
				<view class="w-con">
					<view class="input-row">
						<input class="input-row-w" type="text" v-model="searchVal" placeholder="请输入群名称"
							confirm-type="search" placeholder-style="color:#999"></input>
						<image class="icon-tb3" v-if="searchVal!=''" @click.stop="clear"
							:src="$mAssetsPath.icon_qingchu"></image>
					</view>
				</view>
				<view class="w-but">
					<view class="w-but-txt" @click="cancel('tip')">取消</view>
					<view class="w-but-txt" @click="confirm2">确认</view>
				</view>
			</view>
		</w-popup>
	</view>
</template>

<script>
	import wTit from '@/components/w-tit/w-tit-back-serch-add.vue'; //标题
	import wPhones from '@/components/w-phones/phone-directory1.vue'; //通讯列表
	import wPopup from '@/components/w-popup/w-popup2.vue'; //弹窗
	import {
		mapGetters,
		mapActions
	} from "vuex";
	import {
		getMailLists, //通讯录列表
		getGroupLists, //分组列表
		addGroups, //分组添加
	
	} from '@/common/api.js';
	import TIM from 'tim-js-sdk';
	import store from '@/store';
	export default {
		name: "phones",
		components: {
			wTit,
			wPhones,
			wPopup
		},
		computed: {
			...mapGetters(['companyInfo', 'userInfo']),
		},
		data() {
			return {
				showtip: false, //是否显示弹窗2
				content1: '顶部弹 popup',
				type1: '', //弹窗显示方式
				
				is_shrink: true,
				//示例数据
				phones: [],
				sel_list: [],
				pageType: '',
				id: 1,
				params: {
					company_id: '',
					type: 1,
					nickname: '',
				},
				role_id:'', //页面传参
				flowType:'', //页面传参
				searchVal:'',
				groupID:'',
				member:[],
				list:[]
			}
		},
		onShow() {
			//this.getData();
		},
		onUnload() {
			//页面卸载传值
			/* let callbacke = '';
			if (this.pageType === 'flow') {
				callbacke = 'flow_contactAdd'
			}
			uni.$emit('callback', callbacke, this.id, this.sel_list) */
		},
	    async onLoad(option) {
			console.log(222, option)
			this.params.company_id = this.companyInfo.id;
			if(option.flowType){
				this.flowType = option.flowType;
				if(option.flowType === 'start'){
					this.params.type = 1;
				}else if(option.flowType === 'end'){
					this.params.type = 1;
				}
			}
			if(option.role_id){
				this.role_id = option.role_id
			}
			if (option.pageType) {
				if (option.pageType === 'flow') {
					this.pageType = option.pageType;
					this.id = option.id
				}
				if(option.pageType === 'createGroup'){
					this.pageType = option.pageType;
				}
				if(option.pageType === 'addMember'){
					this.pageType = option.pageType;
				}
				if(option.pageType === 'jianquMember'){
					this.pageType = option.pageType;
					if(option.list){
						this.list = JSON.parse(option.list)
					}
				}
			}
			if(option.groupID){
				this.groupID = option.groupID;
			}
			await this.getdata()
				this.getGysData()
		},
		methods: {
			//获取通讯录列表
			getdata() {
				let _self = this;
				return new Promise((resovle,rej)=>{
				const {params:{type}} = _self
				//获取分组
				getGroupLists({
					company_id: this.params.company_id,
					type: this.params.type
				}).then(res => {
					if (res.code === 2000) {
						// 优化后
						let objlist = res.data
						objlist.length>0&&objlist.unshift({
							id:0,
							name:type===1?'公司分组':type===2?'待分组':''
						})
						// 优化前 代码太多了
						// let objlist = [{
						// 	id:0,
						// 	name:''
						// }]
						// if(this.params.type === 1){
						// 	objlist[0].name = '公司成员';
						// }else if(this.params.type === 2){
						// 	objlist[0].name = '待分组';
						// }
						// if(res.data && res.data.length>0){
						// 	res.data.forEach(ite=>{
						// 		objlist.push(ite)
						// 	})
						// }
						getMailLists(this.params).then(res2 => {
							if (res2.code === 2000) {
								let list = []
								console.log('res11',res)
								if(this.pageType === 'jianquMember'){
									let lists = res2.data;
									if(this.list && this.list.length>0){
										this.list.forEach(item=>{
											if(lists && lists.length>0){
												lists.forEach(ite=>{
													if(ite.uid === item.uid){
														list.push(ite)
													}
												})
											}
										})
									}
								}else{
									list = res2.data;
								}
								if (objlist && objlist.length > 0) {
									objlist.forEach(item => {
										// item.no = 'a'+item.id
										// item.pho = []
										let pho = []
										this.$set(item,'pho',Array)
										this.$set(item,'no','a'+item.id)
										if (list && list.length > 0) {
											list.forEach(item2 => {
											this.$set(item2,'checked',false)
												if (item2.group_id === item.id) {
													pho.push(item2)
												}else if(item2.group_id == null && item.id===0){
													pho.push(item2)
												}
											})
										}
										item.pho = pho;
									})
								}
								this.phones = objlist;
								this.$forceUpdate() //二维数组，开启强制渲染
								console.log(222222, objlist)
								console.log('this.phones',this.phones)
								resovle()
							}
						})
					}
				})
				if(this.pageType === 'jianquMember'){
					let promise = this.tim.getGroupMemberList({ groupID: this.groupID, count: 200, offset:0 }); // 从0开始拉取30个群成员
					promise.then(function(imResponse) {
					  console.log('群成员：',imResponse.data.memberList); // 群成员列表
					  _self.member = imResponse.data.memberList
					  console.log('群成员：',_self.member); // 群成员列表
					}).catch(function(imError) {
					  console.warn('getGroupMemberList error:', imError);
					});
				}
				})
			},
			
			// 获取供应商列表并拼接
			async getGysData(){
				const _this = this
				const{ params} = _this 
				const reqData = {
						company_id: params.company_id,
						type: 2
				}
				let [firstData,secondsData]  = await Promise.all([
					getGroupLists(reqData),
					getMailLists(reqData)
				])
				// 先给组织数据插入一条待分组数据
				firstData.data.unshift({
						id:'a1-1',
						name:'待分组供应商',
						no:'a1-1',
						pho:[]
				})
				// 利用详细数据格式化，一个个塞到组织数据中
				firstData.data.forEach(s=>{
					// 如果没有ID 就存入待分组数据中
					(s['no'] = 'a'+s.id)&&(s['pho'] = s['pho']?[...s['pho']]:[])
					secondsData.data.forEach(v=>{
						v.checked = false
						v.group_id==null&&firstData.data[0].pho.push(v)
						s.id === v.group_id&&(s['no'] = 'a'+s.id)&&(s['pho'] = s['pho']?[...s['pho'],v]:[{...v}])
					})
				})
				this.phones = [...this.phones,...firstData.data]
				console.log(this.phones)
			},
			//创建群
			confirm2(){
				let _self = this;
				if(this.searchVal === ''){
					uni.showToast({
						title:'请输入群名称！',
						icon:'none',
						duration:2000
					})
					return false
				}
				let lists = []
				console.log(22,this.sel_list)
				if (this.sel_list && this.sel_list.length > 0) {
					this.sel_list.forEach(item=>{
						let list = {
							"userID":this.params.company_id + ':' +item.uid
						}
						if(parseInt(item.uid) == parseInt(this.userInfo.uid)){
							
						}else{
							lists.push(list)
						}
					})
					console.log(111,lists)
					// 创建好友工作群
					let promise = this.tim.createGroup({
						type: TIM.TYPES.GRP_WORK, //TIM.TYPES.GRP_MEETING,
						name: this.searchVal,
						// maxMemberNum:200,
						memberList: lists
					});
					promise.then(function(imResponse) { // 创建成功
						// 创建群时指定了成员列表，但是成员中存在超过了“单个用户可加入群组数”限制的情况
						// 一个用户 userX 最多允许加入 N 个群，如果已经加入了 N 个群，此时创建群再指定 userX 为群成员，则 userX 不能正常加群
						// SDK 将 userX 的信息放入 overLimitUserIDList，供接入侧处理
						console.log('建群成功',imResponse); // 超过了“单个用户可加入群组数”限制的用户列表，v2.10.2起支持
						uni.showToast({
							title:'创建群成功！'
						})
						
						/* let promise2 = _self.tim.setGroupMemberRole({
						  groupID: imResponse.data.group.groupID,
						  userID: _self.userInfo.uid + '',
						  role: TIM.TYPES.GRP_MBR_ROLE_ADMIN // 将群 ID: group1 中的用户：user1 设为管理员
						});
						promise2.then(function(imResponse) {
						  console.log(imResponse.data.group); // 修改后的群资料
						  console.log('修改成功！',imResponse.data.member); // 修改后的群成员资料
						 
						}).catch(function(imError) {
						  console.warn('setGroupMemberRole error:', imError); // 错误信息
						}); */
						
						_self.$store.commit('createConversationActives', imResponse.data.group.groupID)
						//加入群
						uni.navigateTo({
							url: `/pages/message/messageInfo?id=${imResponse.data.group.groupID}&name=${imResponse.data.group.name}&type=GROUP`
						})
						
						
					}).catch(function(imError) {
						console.log('创建群失败:', imError); // 创建群组失败的相关信息
					});
					
				}
				this.showtip = false;
			},
			//确认
			confirm() {
				let _self = this;
				if (this.pageType === 'flow') {
					console.log(222222,this.sel_list)
					this.$util.prePage().resdata(this.flowType,this.role_id,this.sel_list);
					setTimeout(() => {
						uni.navigateBack();
					}, 500)
				}else if(this.pageType === 'createGroup'){
					console.log(222222,this.sel_list)
					if(this.sel_list && this.sel_list.length>0){
						this.showtip = true;
						this.content1 = 'center';
						this.type1 = 'center';
						this.searchVal = '';
					}
				}else if(this.pageType === 'addMember'){
					let lists = []
					console.log(22,this.sel_list)
					if (this.sel_list && this.sel_list.length > 0) {
						this.sel_list.forEach(item=>{
							let list = {
								"userID":_self.params.company_id + ':' + item.uid
							}
							if(parseInt(item.uid) == parseInt(this.userInfo.uid)){
								
							}else{
								lists.push(list.userID)
							}
						})
						console.log(111,lists,this.groupID)
						//邀请群成员
						let promise = this.tim.addGroupMember({groupID: this.groupID, userIDList: lists});
						promise.then(function(imResponse) {
						  console.log('添加成功',imResponse.data.successUserIDList); // 添加成功的群成员 userIDList
						  console.log(imResponse.data.failureUserIDList); // 添加失败的群成员 userIDList
						  console.log(imResponse.data.existedUserIDList); // 已在群中的群成员 userIDList
						  // 一个用户 userX 最多允许加入 N 个群，如果已经加入了 N 个群，此时再尝试添加 userX 为群成员，则 userX 不能正常加群
						  // SDK 将 userX 的信息放入 overLimitUserIDList，供接入侧处理
						  console.log(imResponse.data.overLimitUserIDList); // 超过了“单个用户可加入群组数”限制的用户列表，v2.10.2起支持
						  console.log(imResponse.data.group); // 添加后的群组信息
						  uni.showToast({
						  	title:'添加成员成功!',
						  	icon:'none',
						  	duration:2000
						  })
						  setTimeout(() => {
						  	uni.navigateBack({
						  		delta:1
						  	})
						  }, 1000);
						}).catch(function(imError) {
						  console.warn('addGroupMember error:', imError); // 错误信息
						});
						
					}
				}else if(this.pageType === 'jianquMember'){
					let lists = []
					this.sel_list.forEach(item=>{
						let list = {
							"userID":_self.params.company_id + ':' + item.uid
						}
						if(parseInt(item.uid) == parseInt(this.userInfo.uid)){
							
						}else{
							lists.push(list.userID)
						}
					})
					console.log(111,lists,this.groupID)
					let promise = this.tim.deleteGroupMember({groupID: this.groupID, userIDList:lists, reason: '你已被群主移除群了！'});
					promise.then(function(imResponse) {
					  console.log(imResponse.data.group); // 删除后的群组信息
					  console.log('删除成功',imResponse.data.userIDList); // 被删除的群成员的 userID 列表
					  let is_del = '';
					  if(imResponse.data.userIDList && imResponse.data.userIDList.length>0){
						  imResponse.data.userIDList.forEach(item=>{
							  if(_self.member && _self.member.length>0){
								  _self.member.forEach(ite=>{
									  if(item === ite.userID){
										  is_del = '1'
										  uni.showToast({
										  	title:'移除成员成功!',
										  	icon:'none',
										  	duration:2000
										  })
									  }
								  })
							  }
						  })
					  }
					  if(is_del === ''){
						  uni.showToast({
						  	title:'没有该成员!',
						  	icon:'none',
						  	duration:2000
						  })
					  }
					  setTimeout(() => {
					  	uni.navigateBack({
					  		delta:1
					  	})
					  }, 1000);
					}).catch(function(imError) {
					  console.warn('deleteGroupMember error:', imError); // 错误信息
					});
				}
			},
			//接口数据
			getData() {
				if (phones && phones.length > 0) {
					phones.forEach(item => {
						item.pho.forEach(ite => {
							this.$set(ite, 'checked', false)
						})
					})
				}
				this.phones = phones;
			},
			//左侧导航收缩
			navShow(is_shrink) {
				console.log(111, is_shrink)
				this.is_shrink = !is_shrink
			},
			rightSearch() {

			},
			changecheck(uid, checked) {
				console.log(1, uid, checked)
				console.log(2, this.phones)
				if (this.phones && this.phones.length > 0) {
					this.phones.forEach((item, i) => {
						item.pho.forEach((ite, ii) => {
							if (uid === ite.uid) {
								ite.checked = !checked
							}
						})
					})
				}
				let sel_list = []
				if (this.phones && this.phones.length > 0) {
					this.phones.forEach((item, i) => {
						item.pho.forEach((ite, ii) => {
							if (ite.checked === true) {
								this.sel_show = true
								sel_list.push(ite)
							}
						})
					})
					this.sel_list = sel_list;
				}
				console.log(3, this.sel_list)
			},
			paramClick(e) {
				console.log(121, e)
			},
			change1(e) {
				console.log(233, e)
				if (!e.show) {
					this.showtip = false
				}
			},
			//取消
			cancel(type) {
				this['show' + type] = false
			},
			//清空
			clear() {
				this.searchVal = '';
			},
			
		}
	}
</script>

<style lang="scss">
	/* 提示窗口 */
	.w-tip {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		width: 80vw;
		border-radius: 10rpx;
		background-color: #fff;
		box-shadow: 0rpx 7rpx 7rpx 0rpx rgba(0, 0, 0, 0.1);
		margin: 30rpx auto 0;
	
		.w-tit {
			font-size: 36rpx;
			font-weight: bold;
			color: $font-color-3;
			line-height: 60rpx;
			height: 60rpx;
			margin-top: 20rpx;
			text-align: center;
		}
	
		.w-but {
			display: flex;
			font-size: 32rpx;
			font-weight: 400;
			color: $font-color-b3;
			height: 84rpx;
			line-height: 84rpx;
	
			.w-but-txt {
				flex: 1;
				text-align: center;
				border-right: 1rpx solid #f5f5f5;
			}
	
			.w-but-txt:last-of-type {
				border-right: none;
			}
		}
	
		.w-con {
			display: flex;
			text-align: center;
			font-weight: 400;
			padding: 60rpx 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
	
			.input-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				height: 66rpx;
				background: #fff;
				border-radius: 10rpx;
				background: $uni-bg-color-grey;
	
				.icon-tb3 {
					width: 34rpx;
					height: 34rpx;
					margin: 0 20rpx;
				}
	
				.input-row-w {
					padding-left: 30rpx;
					text-align: left;
					font-size: 28rpx;
					font-weight: 400;
					line-height: 20px;
					color: $font-color-9;
					width: calc(100% - 74rpx);
				}
			}
		}
	}
	.titleNview-placing {
		height: var(--status-bar-height);
		box-sizing: content-box;
		background: $uni-bg-color;
		display: block;
		position: sticky;
		top: 0rpx;
		z-index: 9999;
		overflow: hidden
	}

	.page-content {
		display: flex;
		flex-direction: column;
		position: relative;
		height: 100%;
		background: $uni-bg-color-grey;

		.page-foot {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 100rpx;
			width: 100%;
			text-align: center;
			background: #198FFF;
			line-height: 100rpx;
			color: white;
		}

		.page-body {
			display: flex;
			flex-direction: column;
			height: calc(100% - 190rpx - var(--status-bar-height));
		}

		.page-top {
			border-bottom: 1rpx solid $uni-bg-color-grey;
			box-sizing: content-box;
			background: $uni-bg-color;
			display: block;
			position: sticky;
			top: 0rpx;
			z-index: 9999;
		}
	}
</style>
